package com.leectrl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class StorageManager {
    private static StorageManager storageManager;
    private static JSONObject fileContent;
    private static  Map<String,String> cacheMap=new HashMap();
    private StorageManager(){

    }
    public static StorageManager getInstance(){
        if(storageManager==null){
            storageManager=new StorageManager();
        }
        String content=readFile();
        if(content==null){
            fileContent=new JSONObject();
        }else{
            try{
                fileContent= JSON.parseObject(content);
            }catch (Exception e){
                fileContent=new JSONObject();
            }
        }
        return storageManager;
    }

    public static String getItem(String key){
        return fileContent.getString(key);
    }

    public static void setItem(String key, String content){
       fileContent.put(key,content);
       try {
           File file=new File(MyApplication.myApplication.getCacheDir().getAbsoluteFile()+"/storage.txt");
           FileWriter fw = new FileWriter(file);
           fw.write(JSONObject.toJSONString(fileContent));
           fw.flush();
           fw.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

    public static void setCacheItem(String key, String content){
        cacheMap.put(key,content);
    }

    public static String getCacheItem(String key){
       return  cacheMap.get(key);
    }

    protected static String readFile(){
        try {
            File file=new File(MyApplication.myApplication.getCacheDir().getAbsoluteFile()+"/storage.txt");
            if(!file.exists()){
                return null;
            }
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String str2 = br.readLine();
            br.close();
            fr.close();
            return str2;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
